package com.liu.hooks;

import java.io.File;

import com.liu.util.TrackerLoger;

import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedHelpers;

public class ShellHook extends AbstractHook {

	public static final String TAG = "#ShellHook#";
	
	public static final String TYPE = "com.liu.hooks.ShellHook";
	
	public XC_MethodHook shellHook = new XC_MethodHook() {
		@Override
		protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
			
			/**
			 * Parameters
			 * progArray	the array containing the program to execute as well as any arguments to the program.
			 * envp			the array containing the environment to start the new process in.
			 * directory	the directory in which to execute the program. If null, execute if in the same directory as the parent process.
			 * 
			 * Returns
			 * the new Process object that represents the native process.
			 */
			
			TrackerLoger.log(TAG, "[cmds] " + array2string((String[])param.args[0]), TYPE, true);
			TrackerLoger.log(TAG, "[envp] " + array2string((String[])param.args[1]), TYPE, true);
			if(((File)param.args[2]) != null) {
				TrackerLoger.log(TAG, "[file] " + ((File)param.args[2]).getAbsolutePath(), TYPE, true);
			}
			
		}
	};
	
	public String array2string(String[] cmds) {
		
		if(cmds == null) return "";
		StringBuilder sb = new StringBuilder();
		
		for(String s : cmds)
			sb.append(s + " | ");
		
		return sb.toString();
	}
	
	@Override
	public void doHook() {
		XposedHelpers.findAndHookMethod("java.lang.Runtime", classloader, "exec", "java.lang.String[]", "java.lang.String[]", File.class, shellHook);
	}

	@Override
	public void setClassLoader(ClassLoader classloader) {
		this.classloader = classloader;
	}

}
